const express = require('express')
const fileUpload = require('express-fileupload')
const mammoth = require('mammoth')
const path = require('path')
const fs = require('fs')
const app = express()

app.use(fileUpload({
  useTempFiles: true,
  tempFileDir: '/tmp/'
}))

const options = {
  convertImage: mammoth.images.imgElement(function (image) {
    // console.log('image')
    // console.log(image.read("base64"))
    return image.read("base64").then(function (imageBuffer) {
      // const dataBuffer = Buffer.from(imageBuffer, 'base64')
      // const filepath = path.join(__dirname, 'public', 'upload')
      // const filename = 'wordimg' + Date.now() + '.png'

      // fs.writeFile(filepath + '/' + filename, dataBuffer, err => {
      //   console.log('zheyibu')
      //   if (err) {} else {
      //     console.log('到这里就通过了')
          // return {
          //   src: 'sdjflksjdkfjlskdjflkjasdf.png',
          //   alt: 'sdfhskjdhfkjshdfjkshdf'
          // }
      //   }
      // })
      // // console.log('imageBuffer')
      // // console.log(imageBuffer)
      return base64toImg(imageBuffer).then((filename) => {
        console.log('转换成功！')
        return {
          // src: "data:" + image.contentType + ";base64," + imageBuffer
          'src': 'http://localhost:3002/public/upload/' + filename
        };
      }).catch(e => {
        console.log('转换失败！')
      })
    });
  })
};

app.use('/public', express.static(path.join(__dirname, 'public')));

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get('/shuai', (req, res) => {
  res.render('upload');
})

app.post('/shuai/upload', (req, res) => {
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }

  // console.log(req.files)

  let sampleFile = req.files.upload_file;
  let path1 = sampleFile.tempFilePath;
  mammoth.convertToHtml({
      path: path1
    }, options)
    .then(function (result) {
      var html = result.value;
      res.send(html);
    })
    .done();
})

app.listen('3002', function () {
  console.log('listen 3002')
})

function base64toImg(buffer) {
  return new Promise((resolve, reject) => {
    const dataBuffer = Buffer.from(buffer, 'base64')
    const filepath = path.join(__dirname, 'public', 'upload')
    const filename = 'wordimg' + Date.now() + '.png'
    fs.writeFile(filepath + '/' + filename, dataBuffer, err => {
      if (err) {
        reject()
      } else {
        resolve(filename)
      }
    })
  })
}